package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"mange/cache"
	"mange/models"
	"strconv"
)

type MangeController struct {
	beego.Controller
}

func (c *MangeController) Add() {
	userid, _ := c.GetInt("user_id")
	name := c.GetString("name")
	phone := c.GetString("phone")
	address := c.GetString("address")
	mange := models.Mange{
		UserId:  userid,
		Name:    name,
		Phone:   phone,
		Address: address,
	}
	err := models.DB.Create(&mange).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()

}

func (c *MangeController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("id=?", id).Delete(&models.Mange{}).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *MangeController) Edit() {
	id, _ := c.GetInt("id")
	var mange models.Mange
	key := "novel" + strconv.Itoa(id)
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res == "" {
		fmt.Println("从mysql中获取数据")
		models.DB.Where("id=?", id).First(&mange)

		jsonData, _ := json.Marshal(&mange)
		cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	} else {
		fmt.Println("从redis中获取数据")
		json.Unmarshal([]byte(res), key)
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "查询详情成功",
		Data: mange,
	}
	c.ServeJSON()
}
